#include <stdio.h>
#include "usart2.h"
#include "common_func.h"
#include "core_time.h"


void usart2_init() {
    int 	simu_flag = RegRead(0xbf20f500);
    RegWriteb(LCD_UART_BASE + 0x2, 0x03); // reset rx tx
    RegWriteb(LCD_UART_BASE + 0x3, 0x80); // enable dl
    RegWriteb(LCD_UART_BASE + 0x1, 0x00); // dl1
    if(simu_flag) RegWriteb(LCD_UART_BASE + 0x0, 0x1);
    else RegWriteb(LCD_UART_BASE + 0x0, 0x1b); // dl0, 230400
    RegWriteb(LCD_UART_BASE + 0x3, 0x03); // 8N1
    RegWriteb(LCD_UART_BASE + 0x4, 0x00); // modem
}
/**
  * @brief  串口2发送
  * @param  data: 发送的数据
  * @param  len: 数据长度
  * @retval uint8_t: 0成功 其他：失败
  */
uint8_t usart2_send_data(uint8_t *data, uint16_t len)
{
    for (int i = 0; i < len; i++) {
      while (!((*( volatile char * ) ( LCD_UART_BASE + 0x5 )) & 0x20));
        *( volatile char * ) ( LCD_UART_BASE ) = data[i];
    }
    return 0;
}


/**
  * @brief  获取串口2接收fifo的数据
  * @param  buf: 存放的缓冲区
  * @param  len: 需要获取的长度
  * @retval uint16_t: 实际获取到的长度 0表示没有数据可获取
  */
uint16_t usart2_get_rx_data(uint8_t *buf, uint16_t len)
{
    for (int i = 0; i < len; i++) {
        int retry_time = 0;
        while (!((*( volatile char * ) ( LCD_UART_BASE + 0x5 )) & 0x1)) {
          delay_ms(50);
          retry_time++;
          if(retry_time > 10) return i;
        }
        buf[i] = *((volatile unsigned char *)(LCD_UART_BASE));
    }
    return len;
}

/*******************************END OF FILE************************************/



